"""
密钥管理服务
创建时间：2025-09-12
作者：开发团队
目的：处理密钥管理相关业务逻辑
"""

from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime, timedelta, timezone
from ..models.key_management import Key
from ..utils.crypto import generate_key
from ..utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)


def create_key(db: Session, created_by: int, expired_at: datetime | None = None) -> Key:
    """
    创建新密钥
    :param db: 数据库会话
    :param created_by: 创建人ID
    :param expired_at: 过期时间
    :return: 创建的密钥对象
    """
    try:
        # 生成新的加密密钥
        key_content = generate_key().decode()
        
        # 如果没有指定过期时间，默认30天后过期
        if expired_at is None:
            expired_at = datetime.now(timezone.utc) + timedelta(days=30)
        
        # 创建密钥对象
        key = Key(
            content=key_content,
            created_by=created_by,
            expired_at=expired_at,
            status="active"
        )
        
        # 保存到数据库
        db.add(key)
        db.commit()
        db.refresh(key)
        
        logger.info(f"密钥创建成功: ID={key.id}")
        return key
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"创建密钥失败: {str(e)}")
        raise ValueError("创建密钥失败")


def get_keys(db: Session, skip: int = 0, limit: int = 100) -> list[Key]:
    """
    获取密钥列表
    :param db: 数据库会话
    :param skip: 跳过的记录数
    :param limit: 返回的记录数
    :return: 密钥列表
    """
    try:
        return db.query(Key).offset(skip).limit(limit).all()
    except SQLAlchemyError as e:
        logger.error(f"查询密钥列表失败: {str(e)}")
        raise ValueError("查询密钥列表失败")


def get_active_keys(db: Session) -> list[Key]:
    """
    获取活跃密钥列表
    :param db: 数据库会话
    :return: 活跃密钥列表
    """
    try:
        return db.query(Key).filter(
            Key.status == "active",
            (Key.expired_at.is_(None)) | (Key.expired_at > datetime.now(timezone.utc))
        ).all()
    except SQLAlchemyError as e:
        logger.error(f"查询活跃密钥列表失败: {str(e)}")
        raise ValueError("查询活跃密钥列表失败")


def archive_key(db: Session, key_id: int) -> Key | None:
    """
    归档密钥
    :param db: 数据库会话
    :param key_id: 密钥ID
    :return: 更新后的密钥对象或None
    """
    try:
        key = db.query(Key).filter(Key.id == key_id).first()
        if not key:
            return None
        
        setattr(key, 'status', "archived")
        db.commit()
        db.refresh(key)
        
        logger.info(f"密钥归档成功: ID={key.id}")
        return key
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"归档密钥失败: {str(e)}")
        raise ValueError("归档密钥失败")


def activate_key(db: Session, key_id: int) -> Key | None:
    """
    激活密钥
    :param db: 数据库会话
    :param key_id: 密钥ID
    :return: 更新后的密钥对象或None
    """
    try:
        key = db.query(Key).filter(Key.id == key_id).first()
        if not key:
            return None
        
        setattr(key, 'status', "active")
        db.commit()
        db.refresh(key)
        
        logger.info(f"密钥激活成功: ID={key.id}")
        return key
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"激活密钥失败: {str(e)}")
        raise ValueError("激活密钥失败")


def delete_key(db: Session, key_id: int) -> bool:
    """
    删除密钥
    :param db: 数据库会话
    :param key_id: 密钥ID
    :return: 是否删除成功
    """
    try:
        key = db.query(Key).filter(Key.id == key_id).first()
        if not key:
            return False
        
        db.delete(key)
        db.commit()
        
        logger.info(f"密钥删除成功: ID={key_id}")
        return True
    except SQLAlchemyError as e:
        db.rollback()
        logger.error(f"删除密钥失败: {str(e)}")
        raise ValueError("删除密钥失败")